import { useState, useEffect, useCallback, useRef } from "react";
import { Skeleton, Form, TextArea } from 'antd-mobile';
import { QuestionCircleOutline } from 'antd-mobile-icons';
import { Typeahead, Highlighter, Menu as RBTMenu, MenuItem as RBTMenuItem } from 'react-bootstrap-typeahead';
import { DndProvider } from 'react-dnd';
import { isBrowser } from 'react-device-detect';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { TouchBackend } from 'react-dnd-touch-backend';
import { TypingEffect } from '../components/TypingEffect';
import { SubjectRadar } from "../components/SubjectRadar";
import { HobbyWordCloud } from "../components/HobbyWordCloud";
import { TimeAllocationTreeMap } from "../components/TimeAllocationTreeMap";
import { QATypeaheadInputMulti } from "../components/QATypeaheadInputMulti";
import TVList from 'react-tiny-virtual-list';
import introJs from 'intro.js';

export function QA({ qa, onChange }) {
    const [loading, setLoading] = useState(true);
    const [qComplete, setQComplete] = useState({});
    const typeaheadRef = useRef(null);
    const onMoveToken = useCallback(
        (dragIndex, hoverIndex) => {
            const item = qa.answer[dragIndex];
            const newSelected = qa.answer.slice();
            newSelected.splice(dragIndex, 1);
            newSelected.splice(hoverIndex, 0, item);
            onChange(newSelected, true);
        },
        [qa, onChange]
    );
    useEffect(() => {
        let timeout;
        function init() {
            setLoading(true);
            timeout = setTimeout(() => {
                setLoading(false);
            }, 500);
        }
        init();
        return () => clearTimeout(timeout);
    }, [qa?.question]);
    useEffect(() => {
        if (qComplete[0]) {
            introJs().setOptions({
                hintButtonLabel: "好的"
            }).addHints();
        }
    }, [qComplete])
    const filterBy = useCallback((option, props) => {
        return !(qa.answer && qa.answer.findIndex(an => an.label === option.label) > -1) && option.label.startsWith(props.text);
    }, [qa?.answer])
    const renderMenu = useCallback((results, { newSelectionPrefix, paginationText, renderMenuItemChildren, ...menuProps }, props) => {
        const itemHeight = 32;
        return (
            results && results.length === 0 ? null :
                <RBTMenu id={qa.id} {...menuProps}>
                    <div style={{ position: "absolute", right: "10px", opacity: 0.3 }}>点击列表外隐藏联想列表</div>
                    <TVList
                        scrollToIndex={props.activeIndex || 0}
                        scrollToAlignment="auto"
                        height={results.length < 5 ? results.length * itemHeight : 300}
                        itemCount={results.length}
                        itemSize={itemHeight}
                        renderItem={({ index, style }) => {
                            const item = results[index];
                            return (
                                <RBTMenuItem key={index} option={item} position={index} style={style}>
                                    {item.customOption && newSelectionPrefix} <Highlighter search={props.text}>{item.label}</Highlighter>
                                </RBTMenuItem>
                            );
                        }}
                    />
                </RBTMenu>
        );
    }, [qa?.id]);
    return (
        <>
            {
                loading ?
                    <>
                        <Skeleton.Title animated />
                        <Skeleton.Paragraph lineCount={3} animated />
                    </>
                    :
                    <>
                        <Form.Item name={qa.question}
                            label={<div id={`q-${qa.type}`} data-hint-position="bottom-right" data-hint={(qa.type === 0 && "选择学科输入，点击学科可以设置分数，拖动可以移动排名") || undefined}>
                                <QuestionCircleOutline color='#000' />&nbsp;
                                <TypingEffect text={qa.question} speed={5} onComplete={() => setQComplete({ ...qComplete, [qa.type]: true })}>
                                </TypingEffect>
                            </div>}
                        >
                            {
                                qa.selectItems ?
                                    <DndProvider backend={isBrowser ? HTML5Backend : TouchBackend} options={{ enableMouseEvents: true }}>
                                        <Typeahead
                                            autoFocus
                                            id={qa.id}
                                            ref={typeaheadRef}
                                            allowNew={qa.canCustom}
                                            multiple
                                            options={qa.selectItems}
                                            selected={qa.answer || []}
                                            onChange={(selected) => {
                                                onChange(selected);
                                                if (qa.selectItems.length > selected.length) {
                                                    typeaheadRef.current.toggleMenu();
                                                }
                                            }}
                                            placeholder={qa.placeholder}
                                            filterBy={filterBy}
                                            renderMenu={renderMenu}
                                            renderInput={(inputProps, props) => <QATypeaheadInputMulti onScoreChange={v => {
                                                onChange(qa.answer.map(an => an.label === v.label ? v : an));
                                            }} inputProps={inputProps} qa={qa} onMove={onMoveToken} props={props} />}
                                            newSelectionPrefix={"自定义："}
                                            paginate={true}
                                            emptyLabel=""
                                            positionFixed={true}
                                        ></Typeahead>
                                    </DndProvider>
                                    :
                                    <>
                                        <TextArea showCount maxLength={200} style={{ "--color": 'rgb(25, 85, 110)', "border": "1px solid #ced4da", "borderRadius": "0.25rem", "padding": "5px 15px" }} autoFocus value={qa.answer} onChange={onChange}></TextArea>
                                    </>
                            }
                        </Form.Item>
                        {
                            <>
                                {
                                    qa.type === 0 && <>
                                        <SubjectRadar data={qa.answer}></SubjectRadar>
                                    </>
                                }
                                {
                                    qa.type === 1 && <>
                                        <HobbyWordCloud data={qa.answer}></HobbyWordCloud>
                                    </>
                                }
                                {
                                    qa.type === 2 && <>
                                        <TimeAllocationTreeMap data={qa.answer_after_analysis}></TimeAllocationTreeMap>
                                    </>
                                }
                            </>
                        }
                    </>
            }
        </>
    );
}


